<template>
  <div style="background: #f4f7fd">
    <navbar :showHeaderIcon="true" />
    <div class="app-container">
      <div class="fangxiangSelect" v-if="xmxx.selectTypeName == '3+1+2'">
        方向：
        <el-select v-model="type" placeholder="请选择" @change="shaixuanFx">
          <el-option
            v-for="item in direction"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <div class="page-card top-tabs">
        <div class="page-back" @click="$router.back()">
          <i class="el-icon-arrow-left"></i>
          返回
        </div>
        <div class="page-title">
          {{xmxx.examName}} 成绩单
        </div>
      </div>

      <div class="page-card m-top" style="padding-top: 10px">
        <el-tabs v-model="activeComponents" @tab-click="handleClick">
          <el-tab-pane label="总分" name="总分"></el-tab-pane>
          <el-tab-pane
            v-for="item in kslb"
            :key="`subject-${item.name}`"
            :label="item.name"
            :name="item.name"
          ></el-tab-pane>
        </el-tabs>

        <h3>学生成绩</h3>

        <div class="snippet">
          <div>
            红色分数表示科目为学生相对弱势学科，需要重点关注该科目多加练习。
          </div>
          <div>
            蓝色分数表示科目为学生相对优势学科，需要保持成绩，并合理分配时间给其弱势学科中
          </div>
          <div>弱势学科：科目成绩击败率低于总分成绩击败率超过2%的科目。</div>
          <div>优势学科：科目成绩击败率高于总分成绩击败率超过2%的科目。</div>
          <div>
            击败率：测验中低于目标个体成绩的人数百分比，公式为：击败率=(有效参考学生人数-目标名次)
            /（有效参考学生人数-1）。
          </div>
        </div>
        <!-- //总分赋分 -->
        <div v-if="isFfshow">
          <el-input
              v-model="queryParams.studentName"
              placeholder="请输入姓名查询"
              style="width:200px"
              @change="nameInput"
              clearable
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i
            ></el-input>
            <el-input
              v-model="queryParams.admissionNo"
              placeholder="请输入准考证号查询"
              style="width: 200px;margin-left:20px;"
              @change="examNumberinput"
              clearable
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i
            ></el-input>
            <el-table 
                class="m-top" 
                border 
                stripe 
                :data="formattedData"
                v-loading="fullscoreLoading"
              >
                <!-- 准考证号列 -->
                <el-table-column 
                  align="center" 
                  prop="admissionNo" 
                  label="准考证号"
                  width="100"
                  fixed
                ></el-table-column>
                <!-- 姓名列 -->
                <el-table-column 
                  align="center" 
                  prop="studentName" 
                  label="姓名"
                  width="140"
                  fixed
                ></el-table-column>
                <!-- 动态生成各科目列 -->
                <el-table-column 
                  v-for="subject in subjects" 
                  :key="subject" 
                  align="center" 
                  :label="subject"
                >
                  <el-table-column 
                    align="center" 
                    label="分数" 
                    width="100"
                  >
                    <template slot-scope="scope">
                      <!-- 不使用可选链的写法 -->
                      {{ (scope.row.subjects[subject] && scope.row.subjects[subject].totalScore) || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column 
                    align="center" 
                    label="方向联名次" 
                    width="100"
                  >
                    <template slot-scope="scope">
                      {{ (scope.row.subjects[subject] && scope.row.subjects[subject].examRank) || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column 
                    align="center" 
                    label="方向校名次" 
                    width="100"
                  >
                    <template slot-scope="scope">
                      {{ (scope.row.subjects[subject] && scope.row.subjects[subject].schoolRank) || '-' }}
                    </template>
                  </el-table-column>
                  <el-table-column 
                    align="center" 
                    label="方向班名次" 
                    width="100"
                  >
                    <template slot-scope="scope">
                      {{ (scope.row.subjects[subject] && scope.row.subjects[subject].classRank) || '-' }}
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
              <div style="position:fixed;width:100%;left:0;bottom:0;z-index:1000;padding:10px 0;background:#fff;">
                <div style="width:1260px;margin:0 auto">
                  <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="cjdTab"
                  />
                </div>
              </div>
        </div>
        <!-- 单科 -->
        <div v-if="isSsubject">
          <el-input
            v-model="queryParams1.studentName"
            placeholder="请输入姓名查询"
            style="width: 200px"
            @change="nameInput1"
            clearable
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i
          ></el-input>
          <el-input
            v-model="queryParams1.admissionNo"
            placeholder="请输入准考证号查询"
            style="width: 200px; margin-left: 20px"
            @change="examNumberinput1"
            clearable
          >
            <i slot="prefix" class="el-input__icon el-icon-search"></i
          ></el-input>
          <el-table
            class="m-top"
            border
            stripe
            :data="singleSubjectlist"
            v-loading="singleLoading"
          >
            <!-- 固定列 -->
            <el-table-column 
              align="center" 
              label="序号"
              width="80"
              fixed
            >
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              prop="admissionNo"
              label="准考证号"
              width="100"
              fixed
            ></el-table-column>

            <el-table-column
              align="center"
              prop="studentName"
              label="姓名"
              width="140"
              fixed
            ></el-table-column>

            <el-table-column
              align="center"
              prop="className"
              label="班级"
            ></el-table-column>

            <el-table-column
              align="center"
              prop="totalScore"
              label="分数"
            ></el-table-column>

            <el-table-column
              align="center"
              prop="examRank"
              label="方向联考名次"
            ></el-table-column>

            <el-table-column
              align="center"
              prop="schoolRank"
              label="方向学校名次"
            ></el-table-column>

            <el-table-column
              align="center"
              prop="classRank"
              label="方向班级名次"
            ></el-table-column>
            <el-table-column
              v-for="(questionKey, index) in questionKeys"
              :key="questionKey"
              align="center"
              :label="questionHeaders[questionKey]"
              width="180"
            >
              <template slot-scope="scope">
                {{ getQuestionAnswer(scope.row, questionKey) }}
              </template>
            </el-table-column>
            <!-- 动态生成题型列，表头使用basicQuestionName和questionType组合 -->
          </el-table>
          <div
            style="
              position: fixed;
              width: 100%;
              left: 0;
              bottom: 0;
              z-index: 1000;
              padding: 10px 0;
              background: #fff;
            "
          >
            <div style="width: 1260px; margin: 0 auto">
              <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams1.pageNum"
                :limit.sync="queryParams1.pageSize"
                @pagination="singleSubjecttab"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Navbar } from "@/layout/components";
import {
  subjectGetlist,
  studentScoreInfo,
  getStudentSubjectScoreInfo,
} from "@/api/cjfx/cjfx";
export default {
  name: "Cjfx_cjdfx",
  components: {
    Navbar,
  },
  data() {
    return {
      activeComponents: "总分",
      searchName: "",
      kslb: [],
      fftype: 1,
      subjectId: "",
      classId: "",
      isSsubject: false, //单个学科
      isFfshow: true, //赋分
      isScore: false, //总分
      total: 0,
      total1: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        examId: "",
        subjectGroup: "",
        studentName: "",
        admissionNo: "",
      },
      queryParams1: {
        pageNum: 1,
        pageSize: 15,
        examId: "",
        subjectGroup: "",
        studentName: "",
        admissionNo: "",
      },
      type: 1,
      direction: [
        {
          name: "物理方向",
          id: 2,
        },
        {
          name: "历史方向",
          id: 1,
        },
      ],
      // 所有科目列表
      subjects: [],
      xmxx: {},
      fftype: 0,
      formattedData: [],
      singleSubjectlist: [],
      questionTypes: [], // 存储所有题型
      questionKeys: [], // 存储用于标识题型的唯一键
      questionHeaders: {},
      singleLoading: false,
      fullscoreLoading: false,
      type: 2,
    };
  },
  mounted() {
    this.xmxx = JSON.parse(sessionStorage.getItem("analysisXmxx"));
    this.subjectlisttap(this.xmxx.id);
    if (this.$route.query.classId) {
      this.classId = this.$route.query.classId;
    }
    this.cjdTab();
  },
  methods: {
    shaixuanFx(val) {
      this.type = val;
      console.info(this.isSsubject, "this.isSsubject");
      if (this.isSsubject) {
        this.queryParams1.subjectGroup = val;
        this.singleSubjecttab();
      } else {
        this.queryParams.subjectGroup = val;
        this.cjdTab();
      }
    },
    nameInput(val) {
      this.queryParams.studentName = val;
      this.cjdTab();
    },
    examNumberinput(val) {
      this.queryParams.admissionNo = val;
      this.cjdTab();
    },
    nameInput1(val) {
      this.queryParams1.studentName = val;
      this.singleSubjecttab();
    },
    examNumberinput1(val) {
      this.queryParams1.admissionNo = val;
      this.singleSubjecttab();
    },
    //获取学科列表
    subjectlisttap(id) {
      subjectGetlist({
        examId: id,
        endowFlag: this.fftype,
        subjectGroup: 2,
      }).then((response) => {
        if (response.code == 200) {
          this.kslb = response.data;
        } else {
          this.$message({
            message: res.msg,
            type: "warning",
          });
        }
      });
    },
    handleClick(tab, event) {
      this.fftype = tab.name.includes("赋分") ? 1 : 0;
      this.isSsubject = !tab.name.includes("总分"); //单科
      this.isFfshow = tab.name.includes("总分"); //赋分
      this.queryParams.studentName = "";
      this.queryParams.admissionNo = "";
      this.queryParams1.studentName = "";
      this.queryParams1.admissionNo = "";
      if (!tab.name.includes("总分")) {
        let subjectObj = this.kslb.filter((item) => {
          return item.name == tab.name;
        });
        this.subjectId = subjectObj[0].id;
        this.singleSubjecttab();
      } else {
        this.cjdTab();
      }
    },
    async cjdTab(){
      this.subjects = []
      this.formattedData = []
      this.fullscoreLoading = true
      this.queryParams.examId=this.xmxx.id
      this.queryParams.classId = this.classId?this.classId:undefined
      this.queryParams.subjectGroup = this.type;
      const res = await studentScoreInfo(this.queryParams)
      if(res.code==200){
          this.fullscoreLoading = false
          // 处理数据格式，便于表格展示
          this.total = res.total
          this.formattedData = res.rows.map(studentData => {
            const formatted = {
              studentName: studentData[0].studentName,
              admissionNo: studentData[0].admissionNo,
              subjects: {}
            };
            // 收集所有科目
            studentData.forEach(item => {
              formatted.subjects[item.examSubjectName] = item;
              if (!this.subjects.includes(item.examSubjectName)) {
                this.subjects.push(item.examSubjectName);
              }
            });
            return formatted;
          });
      }else{
        this.fullscoreLoading = false
      }
    },
    async singleSubjecttab() {
      this.queryParams1.examId = this.xmxx.id;
      this.queryParams1.endowFlag = this.fftype;
      this.queryParams1.subjectId = this.subjectId;
      this.queryParams1.classId = this.classId ? this.classId : undefined;
      this.queryParams1.subjectGroup = this.type;
      this.singleLoading = true;
      try {
        const res = await getStudentSubjectScoreInfo(this.queryParams1);
        if (res.code === 200) {
          this.total1 = res.total;
          this.singleLoading = false;
          const firstStudentQuestions = res.rows[0]?.studentQuestionVoList || [];
          
          // 关键修改：用数组存顺序，对象存映射
          const questionMap = {}; // 用于快速查询 headerText
          const questionOrder = []; // 严格保存 questionId 的插入顺序

          firstStudentQuestions.forEach((question) => {
            const headerText = `${question.basicQuestionName}${question.questionNumber}`;
            const questionId = question.questionId;
            // 保存映射关系
            questionMap[questionId] = headerText;
            // 记录顺序（避免重复添加，可选）
            if (!questionOrder.includes(questionId)) {
              questionOrder.push(questionId);
            }
          });

          // 后续渲染用 questionOrder 保证顺序，questionMap 查标题
          this.questionKeys = questionOrder; // 顺序与 firstStudentQuestions 一致
          this.questionHeaders = questionMap;

          this.singleSubjectlist = [...res.rows];
        }
      } catch (error) {
        console.error('获取数据失败', error);
        this.singleLoading = false;
      }
    },
    // 获取学生对应题型的答案
    getQuestionAnswer(student, questionId) {
      // 查找当前学生该题的答题数据（questionId需转数字匹配）
      const question = student.studentQuestionVoList.find(
        (item) => item.questionId === Number(questionId)
      );

      if (question) {
        // 显示格式：答案(分数)，可按需调整
        return `${question.studentAnswer || ''} (${question.score}分)`;
      }
      return "无数据"; // 若某学生缺少某题数据，显示提示
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  height: auto;
  width: 1300px;
  margin-left: auto;
  margin-right: auto;
  .fangxiangSelect {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
  }
  .top-tabs {
    display: flex;
    padding: 0;
    padding-right: 24px;
    line-height: 54px;

    .page-back {
      height: 54px;
      color: #ffffff;
      background: #1a48db;
      font-size: 14px;
      font-weight: bold;
      margin-right: 24px;
      padding: 0 10px;
      text-align: center;
      cursor: pointer;
      flex-shrink: 0;
    }

    .page-title {
      font-weight: bold;
    }
  }

  h3 {
    font-weight: bold;
    color: #333;
  }

  .snippet {
    background: #f8f9fa;
    padding: 20px;
    margin-bottom: 20px;
    color: #999999;

    &.danger {
      color: #ea0000;
      background: #ffc7c7;

      h4 {
        color: #ea0000;
      }
    }
    &.mini {
      padding: 5px 20px;
      display: flex;
      align-items: center;
      .el-input {
        width: 100px;
        margin-left: 5px;
      }
    }

    h4 {
      font-weight: bold;
      color: #999999;
    }
    div {
      font-size: 16px;
      line-height: 30px;
    }
  }
}
</style>